package com.ybwh.springboot2.conf;

import com.ybwh.springboot2.common.Constant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket testApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .globalOperationParameters(operationParameters())
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                // base，最终调用接口后会和paths拼接在一起
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ybwh.springboot2"))
                .build();
    }

    /**
     * API文档名称和版本
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("后台管理系统API文档")
                .description("本文档包含用户等相关接口信息;其中日期格式为 yyyy-MM-dd HH:mm:ss,若有其他格式类型则会在model文档中特殊说明")
                // 版本
                .version("1.0")
                .build();
    }

    /**
     * 全局配置参数说明
     *
     * @return
     */
    private List<Parameter> operationParameters() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> params = new ArrayList<Parameter>();
        tokenPar.name(Constant.TOKEN_KEY).description("登录令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).build();
        params.add(tokenPar.build());
        return params;
    }
}
